package com.djakapm.markdown.editor;

import com.djakapm.markdown.editor.util.ExceptionConsumer;
import com.petebevin.markdown.MarkdownProcessor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;

public class Engine {
    public String convert(String markup){
        MarkdownProcessor markupProcessor = new MarkdownProcessor();
        return markupProcessor.markdown(markup);
    }

    public String openDocument(File file){
        String content = null;
        
        try {
            content = FileUtils.readFileToString(file);
            if(StringUtils.isBlank(content)){return null;}
        } catch (IOException e1) {
            ExceptionConsumer.consume(e1);
        }

        return content;
    }
    
    public File saveContent(String filePath,String markdownContent, String markupContent){
        File markdownFile;
        File markupFile;
        String fileName;
        String fullPath;


        if(FilenameUtils.indexOfExtension(filePath) > -1){
            markdownFile = new File(filePath);
        }
        else{
            markdownFile = new File(filePath + AppConstant.DEFAULT_INPUT_FILE_EXT);
        }

        fullPath = FilenameUtils.getFullPath(filePath);
        fileName = FilenameUtils.getBaseName(filePath);
        markupFile = new File(fullPath+fileName + AppConstant.DEFAULT_OUTPUT_FILE_EXT);

        try {
            FileUtils.writeStringToFile(markdownFile,markdownContent);
            FileUtils.writeStringToFile(markupFile,markupContent);
        } catch (IOException e1) {
            e1.printStackTrace();
            return null;
        }

        return markdownFile;
    }
    
    
}
